﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace Clustering
{
    public class ImageListConverter
    {

        public static unsafe Bitmap ListToBitmap(List<double[]> lst, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.FillRectangle(Brushes.Black, 0, 0, width, height);

            for (int i = 0; i < lst.Count; i++)
            {
                bmp.SetPixel(
                    (int)lst[i][0],
                    (int)lst[i][1],
                    Color.FromArgb((int)lst[i][2], (int)lst[i][3], (int)lst[i][4]));
            }

            return bmp;
        }

        public static unsafe List<double[]> BitmapToList(Bitmap image)
        {
            List<double[]> lst = new List<double[]>();

            PixelFormat fmt = (image.PixelFormat == PixelFormat.Format8bppIndexed) ?
    PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb;

            // lock bitmap data
            int width = image.Width;
            int height = image.Height;

            BitmapData imageData = image.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadOnly, fmt);




            // alloc arrays
            int[] r = new int[256];
            int[] g = new int[256];
            int[] b = new int[256];

            int[] rwb = new int[256];
            int[] gwb = new int[256];
            int[] bwb = new int[256];

            byte rv, gv, bv;

            int offset = imageData.Stride - width * 3;

            // do the job
            unsafe
            {
                byte* p = (byte*)imageData.Scan0.ToPointer();

                // for each line
                for (int y = 0; y < height; y++)
                {
                    // for each pixel
                    for (int x = 0; x < width; x++, p += 3)
                    {
                        // get pixel values
                        rv = p[2];
                        gv = p[1];
                        bv = p[0];

                        if (rv + bv + gv > 50)
                        //if ((rv > 180)
                        //    && (gv >180)
                        //    && (bv > 180))
                           lst.Add(new double[] { x, y, rv, gv, bv });

                        //lst.Add(new double[] { x, y, 255, 255, 255 });
                    }
                    p += offset;
                }
            }


            // unlock image
            image.UnlockBits(imageData);


            return lst;
        }
    }
}
